package com.seeyon.apps.kk.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.MapUtils;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.seeyon.apps.kk.constants.Constants;
import com.seeyon.apps.kk.manager.KkEmailStrongManager;
import com.seeyon.cap4.form.api.FormApi4Cap4;
import com.seeyon.cap4.form.bean.FormAuthViewBean;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormBindAuthBean;
import com.seeyon.cap4.form.bean.FormViewBean;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.ctpenumnew.dao.EnumItemDAOImpl;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumItem;
import com.seeyon.ctp.util.json.JSONUtil;
import com.seeyon.v3x.mail.manager.MessageMailManager;

public class KkEmailStrongController extends KkBaseController {
    private KkEmailStrongManager kkEmailStrongManager;

    public MessageMailManager getMessageMailManager() {
        return messageMailManager;
    }

    public void setMessageMailManager(MessageMailManager messageMailManager) {
        this.messageMailManager = messageMailManager;
    }

    private MessageMailManager messageMailManager;

    public KkEmailStrongManager getKkEmailStrongManager() {
        return kkEmailStrongManager;
    }

    public void setKkEmailStrongManager(KkEmailStrongManager kkEmailStrongManager) {
        this.kkEmailStrongManager = kkEmailStrongManager;
    }

    /**
     * 邮件增强请求
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public void showEmailStrong(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String ruleKey = request.getParameter("emailRowsId");
        String formAppId = request.getParameter("formAppId");
        String tableCode = Constants.EmailStrong;

        // 通过模板编号 获取 formTemplateId 和 rightId
        FormApi4Cap4 formApi4Cap4 = (FormApi4Cap4) AppContext.getBean("formApi4Cap4");
        FormBean emailFormBean = formApi4Cap4.getFormByFormCode(tableCode);
        String rightId = "";
        StringBuilder formTemplateId = new StringBuilder();
        Map<String, FormBindAuthBean> formBindAuthBeanMap = emailFormBean.getCheckRuleBean().getFormBean().getBind()
                .getUnFlowTemplateMap(); // formTemplateId
        if (!formBindAuthBeanMap.isEmpty()) {
            for (Entry<String, FormBindAuthBean> entry : formBindAuthBeanMap.entrySet()) {
                formTemplateId.append(entry.getKey());
            }
        }

        List<FormViewBean> formViewBeanList = emailFormBean.getFormViewList();
        for (FormViewBean formViewBean : formViewBeanList) {
            // 获取 pc端视图 ID和权限id
            if (formViewBean.getFormViewType().equals("seeyonform")) {
                rightId = formViewBean.getId() + ".";
                for (FormAuthViewBean formAuthViewBean : formViewBean.getOperations()) {
                    if (formAuthViewBean.getType().equals("update")) {
                        rightId += formAuthViewBean.getId();
                        break;
                    }
                }
                break;
            }
        }

        Map<String, Object> params = Maps.newHashMap();
        params.put("ruleKey", ruleKey);
        params.put("formAppId", formAppId);
        String url = "";
        Map<String, Object> isCheck = this.kkEmailStrongManager.isCheckTable(params);
        if (!isCheck.isEmpty()) {
            Map<String, Object> map = Maps.newHashMap();
            map.put("唯一标识", ruleKey);
            map.put("FORM_APP_ID", formAppId);
            map.put("变量说明", this.kkEmailStrongManager.initFieldDescription(formAppId));

            // 更新预制函数，并打开邮件增强页面
            this.kkEmailStrongManager.updateMailFunction(map);
            url = "/cap4/businessTemplateController.do?method=formContent#/edit?rightId=" + rightId + "&moduleId="
                    + MapUtils.getString(isCheck, "id") + "&formTemplateId=" + formTemplateId.toString()
                    + "&moduleType=42";
        } else {
            // 创建新数据
            Map<String, Object> map = Maps.newHashMap();
            map.put("唯一标识", ruleKey);
            map.put("FORM_APP_ID", formAppId);
            map.put("变量说明", this.kkEmailStrongManager.initFieldDescription(formAppId));
            String moduleId = this.kkEmailStrongManager.insertEamil(tableCode, map);
            url = "/cap4/businessTemplateController.do?method=formContent#/edit?rightId=" + rightId + "&moduleId="
                    + moduleId + "&formTemplateId=" + formTemplateId.toString() + "&moduleType=42";
        }

        // 邮件配置底表修改界面
        Map<String, Object> result = Maps.newHashMap();
        result.put("url", url);
        response.getWriter().print(JSON.toJSON(result));
    }

    /**
     * 保存富文本内容
     *
     * @param request
     * @param response
     * @throws Exception
     */
    public void saveEmailContext(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String id = request.getParameter("id");
        String context = request.getParameter("context");
        Map<String, Object> result = Maps.newHashMap();
        if (!"400".equals(this.kkEmailStrongManager.updateEamilContext(id, context)))
            result.put("code", "200");
        else
            result.put("code", "400");
        response.getWriter().print(JSON.toJSON(result));
    }

    /**
     * 获取信息  回写在富文本控件中
     *
     * @param request
     * @param response
     * @throws Exception
     */
    public void getEmailContext(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String id = request.getParameter("id");
        Map<String, Object> result = Maps.newHashMap();
        result.put("context", this.kkEmailStrongManager.getContext(id));
        response.getWriter().print(JSON.toJSON(result));
    }


    /**
     * 获取自定义控件枚举名称
     *
     * @param request
     * @param response
     * @throws Exception
     */
    public void getEnumName(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String enumIds = request.getParameter("enumId");
        EnumItemDAOImpl numItemDAOImpl = (EnumItemDAOImpl) AppContext.getBean("newEnumItemDAO");
        Map<String, Object> result = Maps.newHashMap();
        String[] enumId = {};
        String value = "";
        CtpEnumItem ctpEnumItem = null;
        try {
            if (-1 != enumIds.indexOf(",")) {
                enumId = enumIds.split(",");
                for (int i = 0; i < enumId.length; i++) {
                    ctpEnumItem = numItemDAOImpl.findById(Long.valueOf(enumId[i]));
                    if (i < enumId.length - 1)
                        value += ctpEnumItem.getShowvalue() + ",";
                    else
                        value += ctpEnumItem.getShowvalue();
                }
            } else {
                ctpEnumItem = numItemDAOImpl.findById(Long.valueOf(enumIds));
                value = ctpEnumItem.getShowvalue();
            }
            result.put("data", value);
        } catch (BusinessException e) {
            e.printStackTrace();
        }
        response.getWriter().print(JSONUtil.toJSONString(result));
    }

    /**
     * 测试发送邮件
     * @param request
     * @param response
     * @throws Exception
     */
    public void  sendMail(HttpServletRequest request, HttpServletResponse response)throws Exception{
        List list = Lists.newArrayList();
        list.add("yuyz@seeyon.com");
        list.add("wtt@seeyon.com");
        boolean flag = this.messageMailManager.sendMessageByMail(list,"邮件发送测试","多人发送",new Date());
        boolean flag1 = this.messageMailManager.sendMessageByMail("yuyz@seeyon.com","邮件发送测试","单人发送",new Date());
        Map<String, Object> result = Maps.newHashMap();
        result.put("mailList","多人发送："+flag);
        result.put("mail","单人发送："+flag1);
        response.getWriter().print(JSONUtil.toJSONString(result));
    }
}